<?php

/**
	Controller Creted By - Mandar Kulkarni
	Dated On - 28-06-2012
*/

class UserController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='main';

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			// perform access control for CRUD operations
		);
	}
	
	public function actions()
    {
        return array(
            // captcha action renders the CAPTCHA image displayed on the register page
            'captcha'=>array(
                'class'=>'CCaptchaAction',
                'backColor'=>0xFFFFFF,
            ),
        );
    }

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	// public function accessRules()
	// {
		// return array(
			// array('allow',  // allow all users to perform 'index' and 'view' actions
				// 'actions'=>array('index','view'),
				// 'users'=>array('*'),
			// ),
			// array('allow', // allow authenticated user to perform 'create' and 'update' actions
				// 'actions'=>array('create','update'),
				// 'users'=>array('@'),
			// ),
			// array('allow', // allow admin user to perform 'admin' and 'delete' actions
				// 'actions'=>array('admin','delete'),
				// 'users'=>array('admin'),
			// ),
			// array('deny',  // deny all users
				// 'users'=>array('*'),
			// ),
		// );
	// }

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		$this->render('view',array(
			'model'=>$this->loadModel($id),
		));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
		Developed By - Mandar Kulkarni
		Developed On - 28-06-2012
		Modified On - 29-06-2012
	 */
	public function actionCreate()
	{
		$model=new User('register');

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['User']))
		{
			$model->attributes=$_POST['User'];
			
			//Set path to store profile image on server
			$target = YiiBase::getPathOfAlias('webroot.profile_images').'/';
			
			if($model->save()){
				$model->password = MD5($_POST['User']['password']);
				
				//Encrypted profile_image name stored in DB and image store on server folder start
				$imageobj=CUploadedFile::getInstance($model,'profile_image');
				
				if(!empty($imageobj)){	
					//Get extension of image
					$ext = $imageobj->type;
					$ext = explode("/",$imageobj->type);
					
					$model->profile_image = md5($imageobj->name).'.'.$ext[1];
					$imageobj->saveAs($target.$model->profile_image);
					//Encrypted profile_image name stored in DB and image store on server folder end
				}
				
				//User type = 0 i.e. YC member while 1st registartion
				$model->user_type = 0;
				
				
				if ($model->save())
				{
					$model->activation_key = $model->userID.rand(1000000, 999999999);
					$model->save();
					// send mail -activation link - http://www.youthconnectindia.com/user_register/user/activate/key/$model->activation_key
					Yii::app()->user->setFlash('profilecreate','Profile Created Successfully and become Youth Connect member.');
				}
				// $this->redirect(array('view','id'=>$model->userID));
				$this->redirect(Yii::app()->homeUrl);
			}
		}

		$this->render('create',array(
			'model'=>$model,
		));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['User']))
		{
			$model->attributes=$_POST['User'];
			if($model->save())
				$this->redirect(array('view','id'=>$model->userID));
		}

		$this->render('update',array(
			'model'=>$model,
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		if(Yii::app()->request->isPostRequest)
		{
			// we only allow deletion via POST request
			$this->loadModel($id)->delete();

			// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
			if(!isset($_GET['ajax']))
				$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
		}
		else
			throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
	}
	
	public function actionYXRegister()
	{
		// $model = new User('yxRegister');
		
		$userID = Yii::app()->session['userID'];
		$userList = User::model()->getModel('USER-ID',array('userID'=>$userID)); 
		$model = $userList;
		$model->scenario = 'yxRegister';
		
		//Set path to store profile image on server
		$target = YiiBase::getPathOfAlias('webroot.profile_images').'/';
		$target1 = YiiBase::getPathOfAlias('webroot.college_id_images').'/';
		
		if($userID){
			if(!empty($_POST['User'])){
				$model->attributes=$_POST['User'];
				
				if($model->save()){
					//Encrypted profile_image name stored in DB and image store on server folder start
					$imageobj=CUploadedFile::getInstance($model,'profile_image');
					$idImageObj=CUploadedFile::getInstance($model,'college_id_image');
					
					if(!empty($imageobj)){	
						//Get extension of image
						$ext = $imageobj->type;
						$ext = explode("/",$imageobj->type);
						
						$model->profile_image = md5($imageobj->name).'.'.$ext[1];
						$imageobj->saveAs($target.$model->profile_image);
						//Encrypted profile_image name stored in DB and image store on server folder end
					}
					
					if(!empty($idImageObj)){
						//Get extension of image
						$ext1 = $idImageObj->type;
						$ext1 = explode("/",$idImageObj->type);
						
						$model->college_id_image = md5($idImageObj->name).'.'.$ext1[1];
						$idImageObj->saveAs($target1.$model->college_id_image);
						//Encrypted college_id_image name stored in DB and image store on server folder end
					}
					
					$model->user_type = 1;
					$model->first_name = $_POST['first_name'];
					$model->last_name = $_POST['last_name'];
					$model->user_name = $_POST['user_name'];
					$model->emailID = $_POST['emailID'];
					$model->address = $_POST['address'];
					$model->save();
					
					if($model->save()){
						$this->redirect('yxRegister');
					}
				}
			}
		}		
		
		$this->render('yx_register_form',array(
			'model'=>$model,'userList'=>$userList
		));
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		$dataProvider=new CActiveDataProvider('User');
		$this->render('index',array(
			'dataProvider'=>$dataProvider,
		));
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new User('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['User']))
			$model->attributes=$_GET['User'];

		$this->render('admin',array(
			'model'=>$model,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	public function loadModel($id)
	{
		$model=User::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='user-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
	
	/**
		Developed By - Mandar Kulkarni
		Developed On - 28-06-2012
	*/
	
	public function actionSearchCity()
	{
		$arrParam =array();
		if(isset($_POST['User']['user_stateID']))
		{	
			//Get state id for which city is to be search
			$Term = $_POST['User']['user_stateID'] ;
			
			$case = "BY-STATE-ID";
			$prompt = "Select City";
		
			$arrParam['stateID'] = isset($Term)?$Term:null ;
			
			//Get list of cities
			$data = City::getList($case,$arrParam);
			
			//Convert object listing data of cities into array of city list
			$data = CHtml::listData($data,'cityID','city_name');
				
			echo CHtml::tag('option',array('value'=>''),$prompt,true);
			foreach($data as $value=>$name)
			{
				echo CHtml::tag('option',array('value'=>$value),CHtml::encode($name));
			}	
		}
		Yii::app()->end();
	}
	
	public function actionActivate($key)
	{
		if ($key)
		{
			$objUser = User::model()->getModel("ACTIVATION-KEY",array('activation_key'=>$key));
			if (!empty($objUser))
			{
				$objUser->activation_key = "";
				$objUser->save();
				Yii::app()->user->setFlash('activationlink','Your profile has been activated successfully. Please Login to Youth Connect');
			}
			else 
				Yii::app()->user->setFlash('activationlink','Account has been already validated or key has been broken.Please try again.');
				
		}
		else
		Yii::app()->user->setFlash('activationlink','Activation link has been broken. Please try again.');
		
		$this->redirect(Yii::app()->homeUrl);
	}
}
